<?php
Yii::import('application.modules.menu.models.*');

class menuService {
    
    public static function listRecipies($model, $selected=-1){
        if ($model !== null){
            $list = "<select name='Recipiedetail[materialid]' id='Recipiedetail_materialid' class='styledselect_form_1'>";
            foreach ($model as $k => $v){
                if ($v->recipieid == $selected)
                    $list .= "<option value='".$v->recipieid."' selected>".$v->drink->drinkname."</option>";
                else
                    $list .= "<option value='".$v->recipieid."'>".$v->drink->drinkname."</option>";
            }
            return $list .= "</select>";
        }        
    }
    
    public static function getMaterialName($materialID){
        $materialModel = Material::model()->find(array(
            'select' => 'materialname',
            'condition' => 'materialid = :id',
            'params' => array(
                ':id' => $materialID,
            )
        ));
        return $materialModel->materialname;
    }
    
    public static function getDrinkName($drinkID){
        $drinkModel = Recipie::model()->find(array(
            'select' => 'drinkname',
            'condition' => 'drinkid = :id',
            'params' => array(
                ':id' => $drinkID,
            )
        ));
    }
    
    public static function getDrinkNameByRecipieID($recipieID){
        $recipieModel = Recipie::model()->find(array(            
            'condition' => 'recipieid = :id',
            'params' => array(
                ':id' => $recipieID,
            )
        ));
        return $recipieModel->drink->drinkname;
    }
    
    /**
     * Default return JSON format of material of drink, if returnType set to "syrup", return JSON format of syrup
     */
    public static function getDrinkRecipe($drinkid, $returnType='material'){
        $recipeDetail = Recipiedetail::model()->findAll(array(
            'join' => 'JOIN recipie ON t.recipieid = recipie.recipieid',
            'condition' => 'drinkid = :drinkid',
            'params' => array(
                ':drinkid' => $drinkid,
            )
        ));
        
        $json = array();
        foreach ($recipeDetail as $detail => $value){
            if ($returnType == 'material')
                $json[$value->materialid] = floatval($value->materialquantity / 100);
            else 
                $json[$value->syrupid] = floatval($value->syrupquantity / 100);
        }
        return CJSON::encode($json);
    }
    
    public static function getCurrentMenyVersion(){
        $config = Config::model()->find(array(
            'condition' => 'name = "Menu Version"'
        ));
        
        return $config->value;
    }
    
    public static function getAmountCoffeesByOrderID($orderID){
        $order = Orderdetail::model()->find(array(
            'select' => 'count(orderid) as sumOrder',
            'condition' => 'orderid = :orderID',
            'params' => array(
                ':orderID' => $orderID,
            )
        ));
        return $order->sumOrder;
    }
    
    public static function getAmountCoffeeByWeek($beginDayTime, $endDayTime, $user){
        $amount = Orderdetail::model()->find(array(
            'select' => 'count(t.orderid) as sumOrder',            
            'join' => 'JOIN orders ON orders.orderid = t.orderid',
            'condition' => 'orderdate between :begin AND :end AND userid = :user',
            'params' => array(
                ':begin' => $beginDayTime,
                ':end' => $endDayTime,
                ':user' => $user
            )
        ));
        
        return $amount->sumOrder;
    }
    
    public static function getAmountRevenueByWeek($beginDayTime, $endDayTime, $user){
        $amount = Orderdetail::model()->find(array(
            'select' => 'sum(drinkprice) as totalPrice',            
            'join' => 'JOIN orders ON orders.orderid = t.orderid JOIN drink ON drink.drinkid = t.drinkid',
            'condition' => 'orderdate between :begin AND :end AND userid =  :user',
            'params' => array(
                ':begin' => $beginDayTime,
                ':end' => $endDayTime,
                ':user' => $user
            )
        ));
        
        return $amount->totalPrice;
    }
    
    public static function getAmountCoffeeByMonth($fromDate, $user){
        $first_minute = mktime(0, 0, 0, date('m', $fromDate), 1);
        $last_minute = mktime(23, 59, 0, date('m',$fromDate), date('t', $first_minute));
        
        $criteria = new CDbCriteria();
        $criteria->select = "count( t.orderid ) as sumOrder , DATE( FROM_UNIXTIME( orderdate ) ) AS statisticsDate";
        $criteria->join = "JOIN orders ON orders.orderid = t.orderid";
        $criteria->condition = "orderdate between :begin AND :end AND userid = :user";
        $criteria->params = array(
            ':begin' => $first_minute,
            ':end' => $last_minute,
            ':user' => $user
        );
        $criteria->group = 'DATE( FROM_UNIXTIME( orderdate))';        
        $amount = Orderdetail::model()->findAll($criteria);
            
        return $amount;
    }
    
    public static function getAmountRevenueByMonth($fromDate, $user){
        $first_minute = mktime(0, 0, 0, date('m', $fromDate), 1);
        $last_minute = mktime(23, 59, 0, date('m',$fromDate), date('t', $first_minute));
        
        $criteria = new CDbCriteria();
        $criteria->select = "sum(drinkprice) as totalPrice, DATE( FROM_UNIXTIME( orderdate ) ) AS statisticsDate";
        $criteria->join = "JOIN orders ON orders.orderid = t.orderid JOIN drink ON drink.drinkid = t.drinkid";
        $criteria->condition = "orderdate between :begin AND :end AND userid = :user";
        $criteria->params = array(
            ':begin' => $first_minute,
            ':end' => $last_minute,
            ':user' => $user
        );
        $criteria->group = 'DATE( FROM_UNIXTIME( orderdate))';   

        $amount = Orderdetail::model()->findAll($criteria);
            
        return $amount;
    }
    
    public static function getAmountCoffeeByYear($fromDate, $user){
        $currentYear = date('Y', $fromDate);
        
        $criteria = new CDbCriteria();
        $criteria->select = 'count( t.orderid ) as sumOrder , MONTH( FROM_UNIXTIME( orderdate ) ) AS statisticsMonth';
        $criteria->join = "JOIN orders ON orders.orderid = t.orderid";
        $criteria->condition = "YEAR(FROM_UNIXTIME( orderdate ))  = :year AND userid = :user";
        $criteria->params = array(
            ':year' => $currentYear,
            ':user' => $user
        );
        $criteria->group = 'MONTH( FROM_UNIXTIME( orderdate))';
        $amount = Orderdetail::model()->findAll($criteria);

        return $amount;        
    }
    
    public static function getAmountRevenuByYear($fromDate, $user){
        $currentYear = date('Y', $fromDate);
        
        $criteria = new CDbCriteria();
        $criteria->select = 'sum(drinkprice) as totalPrice , MONTH( FROM_UNIXTIME( orderdate ) ) AS statisticsMonth';
        $criteria->join = "JOIN orders ON orders.orderid = t.orderid JOIN drink ON drink.drinkid = t.drinkid";
        $criteria->condition = "YEAR(FROM_UNIXTIME( orderdate ))  = :year AND userid = :user";
        $criteria->params = array(
            ':year' => $currentYear,
            ':user' => $user
        );
        $criteria->group = 'MONTH( FROM_UNIXTIME( orderdate))';
        
        $amount = Orderdetail::model()->findAll($criteria);

        return $amount;        
    }
    
    public static function getSyrupNameByID($syrupid, $printPrice=false){
        $syrupModel = Syrup::model()->find(array(
            'condition' => 'syrupid = :id',
            'params' => array(
                ':id' => $syrupid,
            )
        ));
        if (!$printPrice)
            return $syrupModel->syrupname;
        else    return (float)$syrupModel->syrupprice;
    }
    
    public static function getListDrinkSyrup($listSyrup, $printPrice=false){
        $listSyrup = CJSON::decode($listSyrup);
        
        if (is_array($listSyrup)){            
            if ($printPrice){
                $totalPrice = 0;
                foreach ($listSyrup as $syrupid => $addQuantities){
                    $totalPrice += self::getSyrupNameByID($syrupid, true) * (float)$addQuantities;
                }
                return $totalPrice;
            }else{
                $listSyrupNames = "<ul class='list-orders-material'>";                
                foreach ($listSyrup as $syrupid => $addQuantities)
                    $listSyrupNames .= '<li>'.self::getSyrupNameByID($syrupid) . " x " . $addQuantities . "</li>";
                }
                $listSyrupNames .= '</ul>';
                return substr_replace ($listSyrupNames, '', -2);
        }else
            return null;
    }
    
    /**
     * function default get meterial list, if syrup flag set to true, it turn to list the syrup list
     */
    public static function getMaterailListOfRecipie($recipieid, $syrup=false){
        $lists = Recipiedetail::model()->findAll(array(
            'condition' => 'recipieid = :recipieid',
            'params' => array(
                ':recipieid' => $recipieid,
            )
        ));        
        $list = null;
        foreach ($lists as $material => $value){
            if (!$syrup){ //list meterial 
                if (!is_null(self::getMaterialName($value->materialid))){
                    $list .= self::getMaterialName($value->materialid).", ";
                }
            }else{    //list syrup
                if (self::getSyrupNameByID($value->syrupid) != ''){
                    $list .= self::getSyrupNameByID($value->syrupid). ", ";
                }
            }
        }
        return substr_replace($list, '', -2);        
    }
    
    public static function getMaterialNamePrice($materialid, $printPrice=false){
        $material = Material::model()->find(array(
            'condition' => 'materialid = :id',
            'params' => array(
                ':id' => $materialid,
            )
        ));
        
        if ($printPrice)
            return $material->addprice;
        else
            return $material->materialname;
    }
    
    public static function getListDrinkMaterial($listMaterial, $printPrice=false){
        $list = CJSON::decode($listMaterial);
        if (is_array($list)){
            if ($printPrice){                
                $totalPrice = 0;
                foreach ($list as $materialid => $addQuantities){
                    $totalPrice += floatval(self::getMaterialNamePrice($materialid, true))  * $addQuantities;
                }
                return $totalPrice;
            }else{
                $materialNames = "<ul class='list-orders-material'>";
                foreach ($list as $materialid => $addQuantities){
                    $materialNames .= "<li>".self::getMaterialNamePrice($materialid) . " x " . $addQuantities . "</li>";
                }
                return $materialNames."</ul>";
            }
            echo "<hr/>";
        }
    }
    
    public static function getOrangialMaterial($drinkid, $printPrice=false){
        $material = Recipiedetail::model()->findAll(array(
            'select' => 'materialid, materialquantity',
            'join' => 'JOIN recipie ON t.recipieid = recipie.recipieid',
            'condition' => 'drinkid = :drinkid',
            'params' => array(
                ':drinkid' => intval($drinkid),
            )
        ));
        
        if ($printPrice){
            $totalPrice = 0;
            foreach ($material as $key => $value)
                $totalPrice += menuService::getMaterialNamePrice($value->materialid, true);
            return $totalPrice;
        }else{            
            $materialName = "<ul class='list-orders-material'>";
            foreach ($material as $key => $value){  
                if (!is_null(self::getMaterialName($value->materialid))){
                    $materialName .= "<li>".self::getMaterialName($value->materialid) ." x " . ($value->materialquantity / 100) ."</li>";
                }                
            }
            return $materialName."</ul>";            
        }        
    }
    
    public static function getOrangialSyrup($drinkid, $printPrice=false){
        $syrup = Recipiedetail::model()->findAll(array(
            'select' => 'syrupid, syrupquantity',
            'join' => 'JOIN recipie ON t.recipieid = recipie.recipieid',
            'condition' => 'drinkid = :drinkid',
            'params' => array(
                ':drinkid' => intval($drinkid),
            )
        ));
           
        if ($printPrice){
            $totalPrice = 0;
            foreach ($syrup as $key => $value)
                $totalPrice += menuService::getSyrupNameByID($value->syrupid, true);            
            return $totalPrice;
        }else{                        
            $syrupName = "<ul class='list-orders-material'>";
            
            foreach ($syrup as $key => $value){                      
                if (!is_null(self::getSyrupNameByID($value->syrupid))){                    
                    $syrupName .= "<li>".self::getSyrupNameByID($value->syrupid) ." x " . ($value->syrupquantity / 100) ."</li>";
                }                
            }
            return $syrupName."</ul>";            
        }    
    }
        
    public static function getAddQuantityOfMaterial($materialid){
        $material = Material::model()->find(array(
            'condition' => 'materialid = :id',
            'params' => array(
                ':id' => $materialid,
            )
        ));        
    }
    
    public static function getUserList(){
        $users = User::model()->findAll();
        return CHtml::listData($users, 'userid', 'username');
    }
    
    public static function getUnitName($unitID){
        $unit = Unit::model()->find(array(
            'select' => 'unitname',
            'condition' => 'unitid = :id',
            'params' => array(
                ':id' => $unitID,
            )
        ));
        return $unit->unitname;
    }
        
    public static function getListIncomeMaterial($storageID){
        $listMaterial = StorageDetail::model()->findAll(array(
            'condition' => 'storage_id = :id',
            'params' => array(
                ':id' => $storageID,
            )
        ));
        
        $list = null;
        foreach ($listMaterial as $key => $value)
            $list .= $value->material->materialname." , ";
        
        return substr_replace($list, '', -3);
    }
    
    public static function getRecipeDetailByID($recipeid){
        $detail = Recipiedetail::model()->findAll(array(
            'condition' => 'recipieid = :id',
            'params' => array(
                ':id' => $recipeid,
            ),
            'order' => 'materialid, syrupid'
        ));
        
        $list = array();
        if (!is_null($detail)){
            foreach ($detail as $key => $value){
                $list[] = array(
                    'drinkid' => $value->recipieid,
                    'materialid' => $value->materialid,
                    'materialquantity' => $value->materialquantity,
                    'syrupid' => $value->syrupid,
                    'syrupquantity' => $value->syrupquantity,
                );
            }
            return $list;
        }
    }
}

?>
